﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentData;
using WoSoft.PACS.Utility;

namespace PACS.Data
{
    //SQL数据库连接
    public class Db
    {
        #region 数据库连接
        /// <summary>
        /// 获取数据库连接（通过配置）
        /// </summary>
        /// <returns></returns>
        public IDbContext GetConnBySqlserver()
        {
            var db =  new DbContext().ConnectionStringName("default", new SqlServerProvider());
            
            //执行数据库方法
            db.OnExecuting(x =>
            {
                var sql = x.Command.CommandText;
                for (int i = x.Command.Parameters.Count - 1; i >= 0; i--)
                {
                    var item = x.Command.Parameters[i] as System.Data.IDataParameter;
                    sql = sql.Replace(item.ParameterName, String.Format("'{0}'", item.Value));
                }

                //写入执行脚本
                LogHelper.Debug(sql);
                
            });

            //执行完成
            db.OnExecuted(x =>
            {

            });


            //数据库执行异常
            db.OnError(e =>
            {
                var ex = e.Exception;
                LogHelper.Error("数据库执行脚本异常", ex);
                throw ex;
            });

            return db;
        }

        public IDbContext GetConnByOracle()
        {
            return new DbContext().ConnectionString("Data Source=192.168.8.250/rhip;Persist Security Info=True;User ID=rhip;Password=rhip;", new OracleProvider());
        }

        /// <summary>
        /// 获取数据库连接
        /// </summary>
        protected IDbContext SqlDatabase
        {
            get
            {
                return GetConnBySqlserver();
            }
        }
        #endregion

    }
}
